﻿using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

/// Usage:
/// 
/// [System.Serializable]
/// class MyDictionary : SerializableDictionary<int, GameObject> {}
/// class UseDictionAryCalss
/// {
///     [SerializeField]
///     public MyDictionary dic;
/// }
/// 
/// 用法，先创建一个类继承SerializableDictionary<> 并指定泛化类型
/// 然后在具体类
///
///
[System.Serializable]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
    // We save the keys and values in two lists because Unity does understand those.
    [SerializeField]
    private List<TKey> _keys;
    [SerializeField]
    private List<TValue> _values;

    // Before the serialization we fill these lists
    public void OnBeforeSerialize()
    {
        _keys = new List<TKey>(this.Count);
        _values = new List<TValue>(this.Count);
        foreach (var kvp in this)
        {
            _keys.Add(kvp.Key);
            _values.Add(kvp.Value);
        }
    }

    // After the serialization we create the dictionary from the two lists
    public void OnAfterDeserialize()
    {
        this.Clear();
        int count = Mathf.Min(_keys.Count, _values.Count);
        for (int i = 0; i < count; ++i)
        {
            this.Add(_keys[i], _values[i]);
        }
    }

    public static void Save(SerializableDictionary<TKey, TValue> dic,string filePath )
    {//序列化
        FileStream fs = new FileStream(filePath, FileMode.Create);

        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, dic);
        fs.Close();
    }

    public static SerializableDictionary<K, V> Load<K, V>(string filePath)
    { //反序列化
        FileStream fs = new FileStream(filePath, FileMode.Open);
        BinaryFormatter bf = new BinaryFormatter();
        return (SerializableDictionary<K, V>)bf.Deserialize(fs);
    }
}